<template>
  <div class="Row_content" style="width:900px;" id="flybean_create">
    <Form
        inline
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="130">
        <FormItem label="活动名称:" prop="activityName">
          <Input v-model="formValidate.activityName" placeholder="请输入" class='input-wid' :maxlength="20" @on-keyup='filterName' @on-blur="filterName"></Input>
        </FormItem>
        <FormItem></FormItem>
        <FormItem label="开始时间:" prop="activityStart">
          <DatePicker :value="formValidate.activityStart" type="datetime" :editable="false" placeholder="请选择" style="width: 280px" @on-change="activityStartChange" :options="activityStartOptions"></DatePicker>
        </FormItem>
        <FormItem label="结束时间:" prop="activityEnd">
          <DatePicker :value="formValidate.activityEnd" type="datetime" :editable="false" placeholder="请选择" style="width: 280px" @on-change="activityEndChange" :options="activityEndOptions"></DatePicker>
        </FormItem>
        <FormItem label="面向门店:" prop="faceShop">
          <treeselect class="treeselect_box" placeholder="请选择"
              :options="options" style="width:280px;"
              v-model='formValidate.faceShop' multiple value-consists-of="LEAF_PRIORITY"
              :normalizer="normalizer" :limitText='limitText' :limit='1'
              />
        </FormItem>
        <FormItem label="面向会员:" prop="faceMember">
          <Select v-model="formValidate.faceMember" multiple :max-tag-count='4' :max-tag-placeholder='maxTagPlaceholder'>
            <Option v-for="(item, index) in memberLevelList" :value="item.memberLevel" :key="index">{{'V' + item.memberLevel}}</Option>
          </Select>
        </FormItem>
        <div class="add-level" v-if="formValidate.addCouponGift.length>0">
            <FormItem class='chunk' :label="i + 1 + ''" v-for="(ele,i) in formValidate.addCouponGift" :key='i'>
              <Row type='flex' style="width: 600px;">
                <Col>
                  <FormItem  class='level-special1' :rules="{required: true, trigger: 'change', validator: validatePass(i)}" :prop="'addCouponGift.' + i + '.value1'" >
                    <div style="display: flex;width: 280px;">
                      <p>飞豆</p>
                      <p style="margin-left: 10px;margin-right: 5px">当日累计获得</p>
                      <Input placeholder="请输入" style="width:120px" v-model='ele.value1' :value='ele.value1' :maxlength='6' @on-keyup="filterPrice(i, '1')" @on-blur="filterPrice(i, '1')"></Input>
                      <p style="margin-left: 5px">张</p>
                    </div>
                  </FormItem>
                </Col>
                <Col>
                  <FormItem class='level-special2' :prop="'addCouponGift.' + i + '.value2'" :rules="{required: true, trigger: 'change', validator: validatePass2(i)}">
                    <div style="display: flex;margin-left: 50px;width: 150px;">
                      <span style="margin-right: 5px;display:block;width: 24px;text-align:right">{{i === 0 ? '' : '再'}}赠</span>
                      <Input placeholder="请输入" class='input- wid' style="width:80px" v-model='ele.value2' :value='ele.value2' :maxlength='6' @on-keyup="filterPrice(i, '2')" @on-blur="filterPrice(i, '2')"></Input>
                      <span style="margin-left: 5px;">张</span>
                    </div>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
        </div>
        <FormItem label="" class='chunk' prop="addRankNum">
          <Row type='flex' style="width: 700px">
            <Col>
              <Button @click='addGiftNum' :disabled="formValidate.addCouponGift.length === 5 ? true : false">新增一级 +</Button><span style="margin-left:10px;color: #808695;width:130px">最多可设置5个等级</span>
            </Col>
            <Col style="margin-left:218px">
              <Button @click='delLevel' :disabled="formValidate.addCouponGift.length ? false : true">删除一级</Button>
              <span style="margin-left:10px;color: #808695;width:130px">每次删除最后一级</span>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="微信消息模版:" prop="sendMessage">
          <Select v-model="formValidate.sendMessage" @on-change="selectMessageChange">
            <Option v-for="(item, index) in sendMessages"
                    :value="item.id"
                    :key="index">
              {{ item.templateName }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="微信消息内容:" style="width: 830px" v-show="formValidate.sendMessage !== '-1'">
          <Input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            style="width:700px" disabled v-model="message"></Input>
        </FormItem>
        <FormItem class="form-btn" style="margin-top: 5px;display:block">
        <Button type="primary" class="system-submit-btn" @click="handleSubmit">确定</Button>
        <Button class="system-submit-btn" style="margin-left: 8px" @click='handleReset'>取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { routeEqual } from '@/libs/util'
import { editFlyBean } from '@/api/market/flybean.js'
import { getMemberLevelList } from '@/api/member/index'
import { getMessages } from '@/api/market/message'
import { getEmployeeTree } from '@/api/system/employee.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'flybean_create',
  components: { Treeselect },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId,
      userId: state => state.user.userId,
      userName: state => state.user.userName,
      orgId: state => state.user.orgId
    })
  },
  data () {
    return {
      options: [],
      normalizer (node) {
        if (node.childList) {
          if (node.childList.length > 0) {
            return {
              id: node.id,
              label: node.orgName,
              children: node.childList
            }
          } else {
            return {
              id: node.id,
              label: node.orgName
            }
          }
        }
      },
      submitLock: false,
      sendMessages: [{ templateName: '无', id: '-1' }],
      memberLevelList: [],
      categoryList: [],
      message: '',
      formValidate: {
        activityName: '',
        activityStart: '',
        activityEnd: '',
        addRankNum: 0,
        faceMember: [],
        faceShop: [],
        addCouponGift: [
          { value1: '', value2: '' }
        ],
        sendMessage: '-1'
      },
      ruleValidate: {
        activityName: { required: true, message: '请填写活动名称', trigger: 'blur' },
        activityStart: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate.activityStart).getTime()) {
              callback(new Error('请选择开始时间'))
            } else if (new Date(this.formValidate.activityStart).getTime() > new Date(this.formValidate.activityEnd).getTime() || new Date(this.formValidate.activityStart).getTime() === new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('开始时间要小于结束时间'))
            } else {
              callback()
            }
          }
        },
        activityEnd: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('请选择结束时间'))
            } else if (new Date(this.formValidate.activityStart).getTime() > new Date(this.formValidate.activityEnd).getTime() || new Date(this.formValidate.activityStart).getTime() === new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('结束时间要大于开始时间'))
            } else if (new Date().getTime() > new Date(this.formValidate.activityEnd).getTime()) {
              callback(new Error('结束时间要大于当前系统时间'))
            } else {
              callback()
            }
          }
        },
        faceMember: { required: true, message: '请选择面向的会员', type: 'array', trigger: 'change' },
        faceShop: { required: true, message: '请选择面向的门店', trigger: 'change', type: 'array' },
        addRankNum: {
          required: true,
          type: 'number',
          validator: (rule, value, callback) => {
            if (this.formValidate.addCouponGift.length < 1) {
              callback(new Error('等级未设置'))
            } else {
              callback()
            }
          }
        },
        sendMessage: { required: true, message: '请选择短信消息模版' }
      },
      activityStartOptions: {},
      activityEndOptions: {}
    }
  },
  methods: {
    limitText () {
      return '...'
    },
    getOrgTree () { // 获取组织机构树
      getEmployeeTree({
        'merchantId': this.$store.state.user.merchantId,
        'status': 1,
        'orgType': 1
      }).then((res) => {
        if (res.data.status === 200) {
          this.options.push(res.data.data)
        } else {
          this.$Message.error(res.data.error)
        }
      })
    },
    filterName () {
      this.formValidate.activityName = this.formValidate.activityName.replace(/[^0-9A-Za-z\u4e00-\u9fa5]/, '')
    },
    filterPrice (i, level) {
      if (level === '1') {
        let val = this.formValidate.addCouponGift[i].value1
        val = val.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
        this.$set(this.formValidate.addCouponGift[i], 'value1', val)
      } else {
        let val = this.formValidate.addCouponGift[i].value2
        val = val.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
        this.$set(this.formValidate.addCouponGift[i], 'value2', val)
      }
    },
    activityStartChange (time) {
      this.formValidate.activityStart = time
      this.activityEndOptions = {
        disabledDate (date) {
          return date.valueOf() < new Date(time.split(' ')[0]).getTime() - 24 * 3600 * 1000
        }
      }
    },
    activityEndChange (time) {
      this.formValidate.activityEnd = time
      this.activityStartOptions = {
        disabledDate (date) {
          return date.valueOf() > new Date(time).getTime()
        }
      }
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    addGiftNum () {
      if (this.formValidate.addCouponGift.length < 5) {
        this.formValidate.addRankNum++
        this.formValidate.addCouponGift.push({ value1: '', value2: '' })
      }
    },
    delLevel () {
      this.formValidate.addCouponGift.pop()
      this.formValidate.addRankNum--
    },
    handleSubmit () {
      this.$refs.formValidate.validate(val => {
        if (val) {
          let data = {
            merchantId: this.merchantId,
            activityName: this.formValidate.activityName,
            activityStart: this.formValidate.activityStart,
            activityEnd: this.formValidate.activityEnd,
            shopId: this.orgId,
            activityRule: JSON.stringify({
              shopIds: this.formValidate.faceShop,
              memberLevelIds: this.formValidate.faceMember,
              rules: this.formValidate.addCouponGift.map((item, idx) => {
                return {
                  count: item.value1,
                  ticket: item.value2,
                  order: idx + 1
                }
              }),
              templateId: this.formValidate.sendMessage
            }),
            creatorId: this.userId,
            creatorName: this.userName
          }
          if (this.submitLock) {
            return
          }
          this.submitLock = true
          editFlyBean(data).then(res => {
            const result = res.data || {}
            this.submitLock = false
            if (result.status === 200) {
              this.$Message.success('新增成功！')
              this.handleReset()
            } else {
              this.$Message.error(`${result.error}`)
            }
          }).catch(err => {
            this.submitLock = false
            this.$Message.error(`${err}`)
          })
        }
      })
    },
    handleReset () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'flybean_list'
        })
      })
    },
    validatePass2 (i) {
      return (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写数量'))
        } else {
          callback()
        }
      }
    },
    validatePass (i) {
      return (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请填写数量'))
        } else {
          callback()
        }
      }
    },
    // 查询会员等级
    getMemberLevel () {
      getMemberLevelList({
        merchantId: this.$store.state.user.merchantId
      }).then(res => {
        if (res.data.status === 200) {
          this.memberLevelList = res.data.data || []
          if (this.memberLevelList.length > 0) {
            this.memberLevelList = this.memberLevelList.map(item => {
              return {
                memberLevel: item.memberLevel + '',
                memberLevelId: item.memberLevelId
              }
            })
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getEnums (templateType) {
      return new Promise((resolve, reject) => {
        getMessages({
          templateType,
          merchantId: this.$store.state.user.merchantId,
          suitableType: 20,
          status: 1
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.data)
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      })
    },
    selectMessageChange (value) {
      this.formValidate.sendMessage = value
      if (value) {
        this.sendMessages.forEach(item => {
          if (item.id === value) {
            this.message = item.content
          }
        })
      } else {
        this.message = ''
      }
    }
  },
  mounted () {
    this.getMemberLevel()
    this.getOrgTree()
    this.getEnums(1).then(data => {
      this.sendMessages = [{ templateName: '无', id: '-1' }].concat(data || [])
    })
  }
}
</script>

<style lang='less'>
  #flybean_create{
    .del-level{
      position: absolute;
      right: 20px;
      top: 20px;
    }
    .add-level{
      position: relative;
      border: 1px solid #E9E9E9;
      border-radius: 3px;
      margin-bottom: 24px;
      padding-top: 20px;
    }
    .level-special1{
      .ivu-form-item-error-tip {
        left: 112px;
      }
    }
    .level-special2{
      .ivu-form-item-error-tip {
        left: 79px;
      }
    }
    .chunk{
      display: block;
    }
    .treeselect_box {
      display: inline-block;
      span {
        line-height: 18px;
        margin-right: 8px;
      }
    }
    .vue-treeselect__control,
    .vue-treeselect__input-container {
      height: 30px !important;
    }
    .vue-treeselect--has-value .vue-treeselect__multi-value {
      margin-bottom: -4px;
    }
    .vue-treeselect__multi-value-item-container {
      padding-top: 3px;
    }
  }
</style>
